package com.wwp.tbshop.view.fragment;


import android.app.Fragment;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.leon.loopviewpagerlib.FunBanner;
import com.wwp.tbshop.R;
import com.wwp.tbshop.activity.BrandRecommendActivity;
import com.wwp.tbshop.activity.HotProductsActivity;
import com.wwp.tbshop.activity.LimitBuyActivity;
import com.wwp.tbshop.activity.MainActivity;
import com.wwp.tbshop.activity.NewGoodsActivity;
import com.wwp.tbshop.activity.SaleNewsActivity;
import com.wwp.tbshop.activity.SearchActivity;
import com.wwp.tbshop.event.SaleNewsCartEventbus;
import com.wwp.tbshop.manager.FragmentFactory;
import com.wwp.tbshop.model.bean.HomeBean;
import com.wwp.tbshop.model.bean.HomeFragmentPicsBean;
import com.wwp.tbshop.presenter.HomeFragmentPresenter;
import com.wwp.tbshop.util.Constant;
import com.wwp.tbshop.util.UiUtil;
import com.wwp.tbshop.view.adapter.HomeFragmentPicRvAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by 楠GG on 2017/6/14.
 */

public class HomeFragment extends Fragment {

    @Bind(R.id.home_tab)
    LinearLayout mHomeTab;
    @Bind(R.id.item_home_picture_container_indicator)
    FrameLayout mItemHomePictureContainerIndicator;
    @Bind(R.id.goods_tab)
    LinearLayout mGoodsTab;
    @Bind(R.id.goods_items)
    LinearLayout mGoodsItems;
    @Bind(R.id.sale_news)
    ImageView mSaleNews;
    @Bind(R.id.limt_buy)
    ImageView mLimtBuy;
    @Bind(R.id.new_goods)
    ImageView mNewGoods;
    @Bind(R.id.hot_products)
    ImageView mHotProducts;
    @Bind(R.id.brand_recommend)
    ImageView mBrandRecommend;
    @Bind(R.id.homefragment_recyclerview)
    RecyclerView mHomefragmentRecyclerview;
    @Bind(R.id.home_search)
    EditText mHomeSearch;
    @Bind(R.id.homefragment_cart)
    ImageView mHomefragmentCart;

    private List<View> mDatas;
    private int[] mICons;
    private HomeFragmentPresenter mHomeFragmentPresenter;
    private FunBanner mFunBanner;
    private View mLoadingView;

    private int[] homePics = {R.drawable.kindle, R.drawable.coffemachine, R.drawable.usb, R.drawable.battery};
    private int price[] = {799, 4490, 189, 299};
    private int[] marketPrice = {998, 4599, 258, 365};
    private String[] picName = {"kindle电子书", "雀巢全自动咖啡机", "usb连接器", "电池包"};
    private List<HomeFragmentPicsBean> mHomeFragmentPicsBeanList;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.home_fragment, null);
        ButterKnife.bind(this, view);
//        initIcons();
        //创建mHomeFragmentPresenter对象
        mHomeFragmentPresenter = new HomeFragmentPresenter(this);

        /*=============== recyclerview ===============*/
        mHomeFragmentPicsBeanList = new ArrayList<>();
        initData();
        mHomefragmentRecyclerview.setNestedScrollingEnabled(false);//解决滑动失效的问题;

        mHomefragmentRecyclerview.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        HomeFragmentPicRvAdapter adapter = new HomeFragmentPicRvAdapter(this, mHomeFragmentPicsBeanList);
        mHomefragmentRecyclerview.setAdapter(adapter);


        EventBus.getDefault().register(this);
        /*=============== recyclerview ===============*/
        return view;
    }

    private void initData() {
        for (int i = 0; i < homePics.length; i++) {
            HomeFragmentPicsBean bean = new HomeFragmentPicsBean();
            bean.setResId(homePics[i]);
            bean.setPicName(picName[i]);
            bean.setPicPrice(price[i]);
            bean.setPicMarketPrice(marketPrice[i]);
            mHomeFragmentPicsBeanList.add(bean);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mHomeFragmentPresenter.loadHomeInfo();//加载数据;funbanner实现
//        mSubjectGoodsPresenter.loadLimitBuyGoods();
        FunBanner.Builder builder = new FunBanner.Builder(getActivity());
        mFunBanner = builder.setEnableAutoLoop(true)
                .setImageResIds(imgRes)
                .setDotSelectedColor(Color.GREEN)
                .setHeightWidthRatio(0.5556f)
                .setLoopInterval(5000)
                .setEnableAutoLoop(true)
                .setIndicatorBackgroundColor(R.color.colorAccent)
                .build();
//        if ()
        mItemHomePictureContainerIndicator.addView(mFunBanner);

        /*############### 下面是点击跳转 ###############*/
    }

    //跳转到促销快报
    @OnClick({R.id.sale_news, R.id.limt_buy, R.id.new_goods, R.id.hot_products, R.id.brand_recommend, R.id.home_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.sale_news:
                Intent intent = new Intent(UiUtil.getContext(), SaleNewsActivity.class);
                startActivity(intent);
                break;
            case R.id.limt_buy:
                Intent intent2 = new Intent(UiUtil.getContext(), LimitBuyActivity.class);
                startActivity(intent2);
                break;
            case R.id.new_goods:
                Intent intent3 = new Intent(UiUtil.getContext(), NewGoodsActivity.class);
                startActivity(intent3);
                break;
            case R.id.hot_products:
                Intent intent4 = new Intent(UiUtil.getContext(), HotProductsActivity.class);
                startActivity(intent4);
                break;
            case R.id.brand_recommend:
                Intent intent5 = new Intent(UiUtil.getContext(), BrandRecommendActivity.class);
                startActivity(intent5);
                break;
            case R.id.home_search:
//                Intent intent  = new Intent()//跳转到搜索界面
                break;
        }
    }

    private static final String TAG = "HomeFragment";

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }
    /**
     * MAIN线程模型：不管是哪个线程发布事件，都在主线程执行onMainEvent方法
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainEvent(SaleNewsCartEventbus event) {

        //打开mainact中的cartfragment;
        //event.SalenewsToMain(this);//把当前的activity;
//        this.onCheckedChanged(mRgBottomBar,R.id.rb_cart);
        ((MainActivity) getActivity()).changePage(FragmentFactory.createFragmentByPosition(2));
        ((MainActivity) getActivity()).mRgBottomBar.check(R.id.rb_cart);
        event.mActivity.finish();
        /*   changePage(FragmentFactory.createFragmentByPosition(2));
        mRgBottomBar.check(R.id.rb_cart);*/

    }


    public void onHomeServerBug() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getActivity(), "error", Toast.LENGTH_LONG).show();
                mFunBanner.setImageResIds(imgRes);
            }
        });

    }


    public void onHomeError() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getActivity(), "error", Toast.LENGTH_LONG).show();
                mFunBanner.setImageResIds(imgRes);
            }
        });
    }

    int[] imgRes = {R.drawable.home_title_pic3, R.drawable.home_title_pic3, R.drawable.home_title_pic3};
    List<String> picUrls = new ArrayList<>();

    public void onHomeSuccess(final List<HomeBean.HomeTopicBean> list) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (list == null) {
                    mFunBanner.setImageResIds(imgRes);//本地数据
                } else {
                    /**如果picUrls的长度不为list的长度则让ta添加;相等时则一直跳过;*/
                    if (picUrls.size() != list.size()) {
                        for (int i = 0; i < list.size(); i++) {
                            HomeBean.HomeTopicBean homeTopicBean = list.get(i);
                            String pic = homeTopicBean.getPic();
                            picUrls.add(Constant.HOST + pic);
                        }
                    }
                }
                mFunBanner.setImageUrls(picUrls);
            }
        });
    }

    @OnClick({R.id.home_search, R.id.homefragment_cart})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.home_search:
                // TODO: 6/19/2017 ;跳转到搜索界面
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
                break;
            case R.id.homefragment_cart:
                ((MainActivity) getActivity()).changePage(FragmentFactory.createFragmentByPosition(2));
                ((MainActivity) getActivity()).mRgBottomBar.check(R.id.rb_cart);
                break;
        }
    }
}